package at.codebase.web.servlets.ajax;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import at.codebase.db.dao.EApiPartnerDao;
import at.codebase.db.entities.EApiPartner;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.api.ApiPartnerCalls;
import at.codebase.web.util.servlet.SecureServlet;


public class AjaxWorldCloudProvider extends SecureServlet {

	private final static int MAX_RESULTS = 8;

	@Override
	protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}
	
	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ANONYMOUS);
		secLevels.add(UserLevel.REGISTERED);
		secLevels.add(UserLevel.ADMIN);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		JSONArray a = new JSONArray();
		int c = 0;
		try {
			String query = requestInfo.getParameters().getString("query");
			List<EApiPartner> apiPartnerList = EApiPartnerDao.getApiPartnerList();
			EApiPartner randomPartner = apiPartnerList.get((new Random()).nextInt(apiPartnerList.size()));	
			
			JSONObject searchSuggestions = ApiPartnerCalls.getSearchSuggestions(randomPartner, query);
			if(searchSuggestions != null && searchSuggestions.get("success").equals(new Boolean(true))){
				
				JSONArray items = (JSONArray) searchSuggestions.get("items");
				for(int i = 0; i < items.size();i++){
					JSONObject wordWrapper = (JSONObject) items.get(i);
					String string = (String) wordWrapper.get("fullString");
					if(string != null){
						a.add(string.split(" ")[0]);
						c++;
						if(c == MAX_RESULTS)
							break;
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		writer().printInsecure(a.toJSONString());
	}
	
	@Override
	protected String getContentType() {
		return "application/json";
	}

}